
// 92.反转链表II
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int left, int right) {
        // 依旧是使用一个哨兵位
        ListNode* phead = new ListNode;
        phead->next = head;
        ListNode* p = phead;
        for(int i = 0 ; i < left - 1 ; i++)
            p = p->next;
        
        // p 指向first的前一个位置 
        ListNode* prev = nullptr , *cur = p->next;
        for(int i = 0 ; i <= right - left ; i++)
        {
            ListNode* next = cur->next;
            cur->next = prev;
            prev = cur;
            cur = next;
        }

        // 此时cur在right的下一个位置,prev在right位置
        p->next->next = cur;
        p->next = prev;

        return phead->next;
    }
};
